"use strict";

const config = require("../config");
const moment = require("moment");
const _ = require("lodash");
const atwork = require("atwork");

const getBasicResponseData = function(code) {
  return {
    status: code, msg: require("./status_code")[code] || "unknow ecode"
  };
};

const getBasicResponseDataRenderByTemplate = function(code, data) {
  let msg = require("./status_code")[code] || "unknow ecode";
  if (data) {
    msg = _.template(msg)(data);
  }
  return {status: code, msg};
};

const assemblyResponseData = function(code, additionalData, templateData) {
  const responseData = getBasicResponseDataRenderByTemplate(code, templateData);
  responseData.results = additionalData;
  return responseData;
};

const getResponseFunc = function(res) {
  res.setHeader("P3P","CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");
  const success = function(data, code) {
    const returnedData = assemblyResponseData(code || "ok", data);
    res.json(returnedData);
    return data;
  };
  const fail = function(e) {
    let error = e;
    if (!(error instanceof Error)) {
      console.log("需要更新遗留代码的错误抛出方式啦", e);
      error = new Error("88888");
    }
    const returnedData = assemblyResponseData(error.message, error.additionalData, error.templateData);
    console.log("fail", returnedData);
    res.json(returnedData);
    console.log(e, e.stack);
    return e;
  };
  const warning = function(error) {
    const returnedData = assemblyResponseData(error.message, null, error.templateData);
    res.json(returnedData);
    return error;
  };
  return {success, fail, warning};
};

const getAtworkInstance = function(ctx) {
  if (!ctx || !ctx.domainId || !ctx.orgId) {
    console.error("参数不足", ctx);
    throw new Error("e_params");
  }
  return getAtworkSimpleInstance(ctx);
};

const getAtworkSimpleInstance = function(ctx) {
  const param = {
    clientId: ctx.clientId || config.privateConfig.clientId,
    clientSecret: ctx.clientSecret || config.privateConfig.clientSecret,
    adminServer: ctx.adminServer || config.privateConfig.apiServer.internal,
    domainId: ctx.domainId,
    orgId: ctx.orgId
  };
  return atwork(param);
};

const escapeChars = {
    "&": "&amp;",
    "'": "&apos;",
    '"': "&quot;",
    "<": "&lt;",
    ">": "&gt;",
    "\n": "</br>"
};

const escapeString = (str) => {
    for (let key in escapeChars) {
        var reg = new RegExp(key, "g");
        str = str.replace(reg, escapeChars[key])
    }
    return str;
}

const escapeObj = (obj) => {
    for (let key in obj) {
        if ("string" === typeof obj[key]) {
            obj[key] = escapeString(obj[key])
        } else {
            escapeObj(obj[key]);
        }
    }
    return obj;
}

const getInfoByReq = (req) => {
  if (!req.session || !req.session.account){
      throw new Error("e_invalid_session")
  }
  return req.session.account;
}

const getAndValidatePagingParams = (params) => {
  let {pageIndex, pageSize} = params;
  pageIndex = parseInt(pageIndex);
  pageSize = parseInt(pageSize);
  if (!Number.isInteger(pageSize) || !Number.isInteger(pageIndex)) {
    throw new Error("e_params");
  }
  return {pageIndex, pageSize}
}

const soapRequest = (url, fnName, args) => {
  console.log(`====SoapRequest:${url}\nfnName:${fnName}\nargs:${JSON.stringify(args)}====`);
  return new Promise(function(resolve, reject){
    soap.createClient(url,{
      wsdl_options: {
        timeout: 3000
      }
    }, function(err, client) {
      if(err || !client){
        reject(err);
        return;
      }
      client[fnName](args, function(err, result) {
        if (err) {
          console.log(`===SoapError:${url}-soap-response====:${err}`);
          reject(err);
        } else {
          console.log(`===SoapSuccess:${url}====:${JSON.stringify(result).substring(0, 100)}`);
          resolve(result);
        }
      });
    });
    // reject();
  })
}

module.exports = {
  getResponseFunc,
  getAtworkInstance,
  escapeObj,
  getInfoByReq,
  getAndValidatePagingParams,
  soapRequest
}
